package Main.CS2.client;


import Main.CS2.entity.Contact;
import Main.CS2.dao.ContactDao;
import org.apache.ibatis.session.SqlSession;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableCellRenderer;
import javax.swing.table.TableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


public class MainJFrame {


    JFrame jf;
    JPanel jp;
    JTabbedPane jtbp;
    Font font;

    JTextField SearchText;
    JButton SearchButton;
    JButton AddButton;

    MainJFrame() {
        jf = new JFrame("个人通讯录系统(软件体系结构实验3)/CS2");
        jf.setLocationRelativeTo(null);
        jf.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);//窗口关闭
        font = new Font("宋体", Font.BOLD, 16);
        SearchText = new JTextField(20);
        SearchText.setText("");
        jtbp = new JTabbedPane();
        SearchButton = new JButton("查询");
        AddButton = new JButton("新增");
    }


    public void display() {
        jf.setSize(800, 600);//设置窗口大小


        jp = getJp();
        jf.add(jp);
        //显示窗口（把内存中的窗口显示在屏幕上）
        jf.setVisible(true);
    }


    private JPanel getJp() {
        JPanel jp = new JPanel();
        jp.setLayout(null);
        JLabel tip = new JLabel("联系人姓名:");
        tip.setFont(font);
        tip.setBounds(100, 10, 200, 50);
        jp.add(tip);


        SearchText.setBounds(200, 20, 200, 30);
        jp.add(SearchText);


        SearchButton.setFont(font);
        SearchButton.setBounds(450, 10, 100, 60);
        jp.add(SearchButton);


        AddButton.setFont(font);
        AddButton.setBounds(655, 10, 100, 60);
        jp.add(AddButton);

        final Object[] header = {"编号", "姓名", "地址", "电话", "", ""};

        System.out.println(SearchText.getText());
        final JTable result = new JTable(getResultContent(), header);
        JScrollPane jScrollPane = new JScrollPane(result);
        result.setBounds(20, 100, 750, 600);
        jScrollPane.setBounds(20, 100, 750, 600);
        jp.add(jScrollPane);

        try {
            result.getColumnModel().getColumn(4).setCellEditor(new MyRenderForUpdate());
            result.getColumnModel().getColumn(4).setCellRenderer(new MyRenderForUpdate());
            result.getColumnModel().getColumn(5).setCellEditor(new MyRenderForDelete());
            result.getColumnModel().getColumn(5).setCellRenderer(new MyRenderForDelete());
        } catch (IOException e) {
            e.printStackTrace();
        }


        SearchButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                TableModel tableModel = new DefaultTableModel(getResultContent(), header);
                result.setModel(tableModel);
                try {
                    result.getColumnModel().getColumn(4).setCellEditor(new MyRenderForUpdate());
                    result.getColumnModel().getColumn(4).setCellRenderer(new MyRenderForUpdate());
                    result.getColumnModel().getColumn(5).setCellEditor(new MyRenderForDelete());
                    result.getColumnModel().getColumn(5).setCellRenderer(new MyRenderForDelete());
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });

        AddButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
               new JFrameManager().contactAddJFrame.display();

            }
        });

        return jp;
    }


    public Object[][] getResultContent() {

        List<Contact> result = new ArrayList<Contact>();
        if (SearchText.getText().length() <= 0 || SearchText.getText() == null) {
            result = MySqlSession.getSession().getMapper(ContactDao.class).contactSelectAll();
        } else {
            result = MySqlSession.getSession().getMapper(ContactDao.class).contactSelectByName("%" + SearchText.getText() + "%");
        }
        Object[][] resultContent = new Object[result.size()][6];
        for (int i = 0; i < result.size(); i++) {
            Contact contact = result.get(i);
            resultContent[i][0] = contact.getCcode();
            resultContent[i][1] = contact.getCname();
            resultContent[i][2] = contact.getCaddress();
            resultContent[i][3] = contact.getCphone();
            resultContent[i][4] = contact.getCcode();
            resultContent[i][5] = contact.getCcode();

        }

        return resultContent;
    }


}

class MyRenderForUpdate extends AbstractCellEditor implements TableCellRenderer, ActionListener, TableCellEditor {
    private JButton button = null;
    private int currentCCode;

    public MyRenderForUpdate() throws IOException {
        button = new JButton("修改");
        button.addActionListener(this);
    }

    @Override
    public Object getCellEditorValue() {
        // TODO Auto-generated method stub
        return currentCCode;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        // TODO Auto-generated method stub
        return button;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        new JFrameManager().contactUpdateJFrame.display(currentCCode);
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected, int row, int column) {
        // TODO Auto-generated method stub
        this.currentCCode = (int) value;
        return button;
    }

}


class MyRenderForDelete extends AbstractCellEditor implements TableCellRenderer, ActionListener, TableCellEditor {
    private JButton button = null;
    private Integer currentCCode;

    public MyRenderForDelete() throws IOException {
        button = new JButton("删除");
        button.addActionListener(this);
    }

    @Override
    public Object getCellEditorValue() {
        // TODO Auto-generated method stub
        return currentCCode;
    }

    @Override
    public Component getTableCellRendererComponent(JTable table, Object value,
                                                   boolean isSelected, boolean hasFocus, int row, int column) {
        // TODO Auto-generated method stub
        return button;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // TODO Auto-generated method stub
        SqlSession session = MySqlSession.getSession();
        session.getMapper(ContactDao.class).contactDelete(currentCCode);
        session.commit();
        JOptionPane.showMessageDialog(null, "删除成功", "消息", JOptionPane.OK_OPTION);
        JFrameManager.mainJFrame.SearchButton.doClick();
        button.removeNotify();
    }

    @Override
    public Component getTableCellEditorComponent(JTable table, Object value,
                                                 boolean isSelected, int row, int column) {
        // TODO Auto-generated method stub
        this.currentCCode = (Integer) value;
        return button;
    }
}